package com.wbao.dianniu.ui;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.util.Linkify;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.R;
import com.wbao.dianniu.adapter.AmAnswerAdapter;
import com.wbao.dianniu.adapter.NoScrollGridAdapter;
import com.wbao.dianniu.customView.CustomDialog;
import com.wbao.dianniu.customView.LoadingWaitDialog;
import com.wbao.dianniu.customView.MyListView;
import com.wbao.dianniu.customView.NoDoubleClickListener;
import com.wbao.dianniu.data.QaResponse;
import com.wbao.dianniu.data.QuestAnswerCountsData;
import com.wbao.dianniu.data.QuestAnswerListData;
import com.wbao.dianniu.emojiUtils.EmotionMainFragment;
import com.wbao.dianniu.http.ErrorCode;
import com.wbao.dianniu.listener.IAnswerDeleteListener;
import com.wbao.dianniu.listener.IPraiseListener;
import com.wbao.dianniu.listener.IQuestAnswerListListener;
import com.wbao.dianniu.listener.IQuestAnswerListener;
import com.wbao.dianniu.listener.IQuestDelListener;
import com.wbao.dianniu.listener.IQuestDetailListener;
import com.wbao.dianniu.logical.Const;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.update.AmDataChangeManager;
import com.wbao.dianniu.manager.AnswerDeleteManger;
import com.wbao.dianniu.manager.BrowseAddManger;
import com.wbao.dianniu.manager.PraiseManger;
import com.wbao.dianniu.manager.QAnswerListManger;
import com.wbao.dianniu.manager.QuestAnswerManager;
import com.wbao.dianniu.manager.QuestDelManager;
import com.wbao.dianniu.manager.QuestDetailManager;
import com.wbao.dianniu.update.ShareSDKManager;
import com.wbao.dianniu.scrollview.PullToRefreshView;
import com.wbao.dianniu.scrollview.PullToRefreshView.OnFooterRefreshListener;
import com.wbao.dianniu.update.ErrorDialogHelper;
import com.wbao.dianniu.utils.CommentLongClickHelper;
import com.wbao.dianniu.utils.JsonUtil;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.utils.PictureDownloadUtils;
import com.wbao.dianniu.utils.ReplyHelper;
import com.wbao.dianniu.utils.ReportType;
import com.wbao.dianniu.utils.Utils;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 匿名详情页
 *
 * @author yejianjun
 */
public class AmDetailActivity extends AppCompatActivity implements IQuestAnswerListListener, IQuestAnswerListener, IPraiseListener,
        IAnswerDeleteListener, OnFooterRefreshListener, OnClickListener, ReplyHelper.ReplyListener, IQuestDelListener,
        IQuestDetailListener,CommentLongClickHelper.ICommentLongListener {

    private LinearLayout waittingLayout;
    private ProgressBar waittingProBar;
    private TextView waittingTV;

    /**
     * 标题左侧的返回按键
     */
    private ImageButton backBtn;
    /**
     * 标题
     */
    private TextView titleTV;
    /**
     * 标题右边图片
     */
    private ImageButton rightImageBtn;
    /**
     * 内容
     */
    public TextView contentTV;
    /**
     * 转发数
     */
    public TextView forwardTV;
    /**
     * 点赞数
     */
    private TextView praiseTV;
    /**
     * 回复数
     */
    private TextView answerTV;
    /**
     * 浏览数
     */
    private TextView visitorTV;
    private TextView deleteTV;
    private int questId;
    private AmAnswerAdapter adapter;
    private QAnswerListManger manager;
    private QuestAnswerManager qAnswerManager;
    private QuestDelManager questDelManager;
    private QuestDetailManager questDetailManager;
    /**
     * 回答列表listview
     */
    private MyListView myListView;
    private Dialog dialog;
    private GridView mGridView;
    private TextView aliasNameTV;
    private List<QuestAnswerListData> mList = new ArrayList<QuestAnswerListData>();
    private AnswerDeleteManger deleteManager;
    private ScrollView mScrollView;
    private final int PAGE_COUNTS = 10;
    private int currentPage = 0;
    private PullToRefreshView mPullToRefreshView;
    private Map<Integer, String> replyMap = null;
    private QaResponse resp;

    private RelativeLayout mInfoRL;
    private EmotionMainFragment emotionMainFragment;
    private EditText bar_edit_text;
    private ImageView bar_image_add_btn;
    private Button bar_btn_send;
    private InputMethodManager mInputManager;//软键盘管理类
    private CommentLongClickHelper commentLongClickHelper;
    private AmDataChangeManager amDataChangeManager;
    private PraiseManger praiseManger;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // 系统版本大于19
            Utils.setTranslucentStatus(this,true);
			SystemBarTintManager tintManager = new SystemBarTintManager(this);
			tintManager.setStatusBarTintEnabled(true);
			tintManager.setStatusBarTintResource(R.color.title_bg);// 通知栏所需颜色
		}
        setContentView(R.layout.activity_am_detail);
        amDataChangeManager = AmDataChangeManager.getInstance();
        initWattingView();
        initBaseView();
        initView();
        pullData();
        initData();
        requestData(currentPage);
        initEmotionMainFragment();
    }

    /**
     * 初始化表情面板
     */
    public void initEmotionMainFragment() {
        mInputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        //构建传递参数
        Bundle bundle = new Bundle();
        //绑定主内容编辑框
        bundle.putBoolean(EmotionMainFragment.BIND_TO_EDITTEXT, true);
        //隐藏控件
        bundle.putBoolean(EmotionMainFragment.HIDE_BAR_EDITTEXT_AND_BTN, false);
        //替换fragment
        //创建修改实例
        emotionMainFragment = EmotionMainFragment.newInstance(EmotionMainFragment.class, bundle);
        emotionMainFragment.bindToContentView(mInfoRL, bar_image_add_btn, bar_edit_text);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        // Replace whatever is in thefragment_container view with this fragment,
        // and add the transaction to the backstack
        transaction.replace(R.id.fl_emotionview_main, emotionMainFragment);
        transaction.addToBackStack(null);
        //提交修改
        transaction.commit();
    }

    private void initWattingView() {
        waittingLayout = (LinearLayout) findViewById(R.id.waitting_layout);
        waittingProBar = (ProgressBar) findViewById(R.id.waitting_progress);
        waittingTV = (TextView) findViewById(R.id.waitting_text_desc);
    }

    private void initData() {
        String id = getIntent().getStringExtra(Const.INTENT_SCHEME_ID);
        if (null != id) {
            questId = Integer.valueOf(id);
            // 单独请求下detail接口
            questDetailManager = new QuestDetailManager(this);
            questDetailManager.addQuestDetailListener(this);
            questDetailManager.questDetail(GlobalContext.getAccountId(), questId);
        }

        BrowseAddManger browseManager = new BrowseAddManger(this);
        browseManager.browseAdd(GlobalContext.getAccountId(), questId);
        manager = new QAnswerListManger(this);
        manager.addListener(this);
        deleteManager = new AnswerDeleteManger(this);
        deleteManager.addAnswerDeleteListener(this);
        qAnswerManager = new QuestAnswerManager(AmDetailActivity.this);
        qAnswerManager.addQuestAnswerListener(this);
        questDelManager = new QuestDelManager(this);
        questDelManager.addQuestDelListener(this);
        adapter = new AmAnswerAdapter(this);
        adapter.addData(mList, new QuestAnswerCountsData());
        myListView.setAdapter(adapter);
        setListViewHeightBasedOnChildren(myListView);

        // 回复@功能监听
        ReplyHelper.getInstance().addReplyListener(this);
        commentLongClickHelper = CommentLongClickHelper.getInstance();
        commentLongClickHelper.addCommentLongClickListener(this);
    }

    private void requestData(int page) {
        manager.requestAnswerList(GlobalContext.getAccountId(), String.valueOf(questId), page * PAGE_COUNTS, PAGE_COUNTS);
    }

    private void initView() {
        myListView = (MyListView) findViewById(R.id.am_detail_list);

        mPullToRefreshView.setOnFooterRefreshListener(this);
        mPullToRefreshView.setLastUpdated(new Date().toLocaleString());
    }

    private void initBaseView() {
        backBtn = (ImageButton) findViewById(R.id.back_button);
        backBtn.setOnClickListener(this);
        titleTV = (TextView) findViewById(R.id.title);
        titleTV.setText("查看匿名");
        rightImageBtn = (ImageButton) findViewById(R.id.right_imagebutton);
        rightImageBtn.setVisibility(View.VISIBLE);
        rightImageBtn.setImageResource(R.drawable.sandian);
        rightImageBtn.setOnClickListener(this);

        mPullToRefreshView = (PullToRefreshView) findViewById(R.id.am_pull_to_refresh_view);
        mScrollView = (ScrollView) findViewById(R.id.am_scrollview);
        aliasNameTV = (TextView) findViewById(R.id.am_alias_name);
        contentTV = (TextView) findViewById(R.id.am_content_tv);
        visitorTV = (TextView) findViewById(R.id.include_visitor_tv);
        deleteTV = (TextView) findViewById(R.id.include_delete_tv);
        forwardTV = (TextView) findViewById(R.id.include_forward_tv);
        praiseTV = (TextView) findViewById(R.id.include_praise_tv);
        answerTV = (TextView) findViewById(R.id.include_answer_tv);
        praiseTV.setOnClickListener(this);
        deleteTV.setOnClickListener(this);
        forwardTV.setOnClickListener(this);
        mGridView = (GridView) findViewById(R.id.am_detail_gridview);
        mInfoRL = (RelativeLayout) findViewById(R.id.content_relayout);

        bar_image_add_btn = (ImageView) findViewById(R.id.bar_image_add_btn);
        bar_btn_send = (Button) findViewById(R.id.bar_btn_send);
        bar_btn_send.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                String comment = bar_edit_text.getText().toString().trim();
                if (null == comment || "".equals(comment)) {
                    Notification.toast(AmDetailActivity.this, "请输入你的评论!");
                    return;
                }
                addAnswerComment(comment);
                // 隐藏键盘
                emotionMainFragment.onBackPress();
            }
        });
        bar_edit_text = (EditText) findViewById(R.id.bar_edit_text);
        bar_edit_text.setOnClickListener(this);
        bar_edit_text.setOnEditorActionListener(actionListener);
        bar_edit_text.addTextChangedListener(watcher);

    }

    private void pullData() {
        Intent intent = getIntent();
        resp = new QaResponse();
        Bundle bundle = intent.getBundleExtra(Const.AM_DATA_BUNDLE);
        if (null != bundle) {
            resp.realName = bundle.getString(Const.BUNDLE_REALNAME);
            resp.content = bundle.getString(Const.BUNDLE_CONTENT);
            resp.visitorCount = bundle.getInt(Const.BUNDLE_VISITORCOUNT);
            resp.forwardCount = bundle.getInt(Const.BUNDLE_FORWARDCOUNT);
            resp.questImgs = bundle.getString(Const.BUNDLE_QUESTIMGS);
            resp.goodCount = bundle.getInt(Const.BUNDLE_GOODCOUNT);
            resp.answerCount = bundle.getInt(Const.BUNDLE_ANSWERCOUNT);
            resp.isGood = bundle.getInt(Const.BUNDLE_ISGOOD);
            resp.accountId = bundle.getInt(Const.BUNDLE_ACCOUNTID);
            questId = bundle.getInt(Const.BUNDLE_QUESTID);

            display(resp);
        }

    }

    @Override
    public void onBackPressed() {
        /**
         * 判断是否拦截返回键操作
         */
        if (!emotionMainFragment.isInterceptBackPress()) {
            // 注释这段代码 这个会双击才能退出
            //super.onBackPressed();
            finish();
        }
    }


    // 上拉刷新数据请求
    private void pullUpRequest() {
        //没有搜索结果 或者数据为空 上拉没有效果
        currentPage++;
        requestData(currentPage);
    }

    OnEditorActionListener actionListener = new OnEditorActionListener() {

        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEND /*||(event!=null&&event.getKeyCode()== KeyEvent.KEYCODE_ENTER)*/) {
                String comment = bar_edit_text.getText().toString().trim();
                if (null == comment || "".equals(comment)) {
                    Notification.toast(AmDetailActivity.this, "请输入你的评论!");
                    return false;
                }
                addAnswerComment(comment);
                // 隐藏键盘
                emotionMainFragment.onBackPress();
//                Utils.hideSoftInput(AmDetailActivity.this, bar_edit_text);
                return true;
            }
            return false;
        }
    };

    private void addAnswerComment(String comment) {
        if (null != replyMap) {
            for (Map.Entry<Integer, String> entry : replyMap.entrySet()) {
                comment = "回复" + entry.getValue() + ":" + comment;
            }
        }
        // 回复之前 增加等待框
        dialog = LoadingWaitDialog.createLoadingDialog(this, "");
        dialog.setCancelable(false);
        dialog.show();
        qAnswerManager.addResponse(GlobalContext.getAccountId(), questId, comment, JsonUtil.mapToStringJson(replyMap));
    }

    @Override
    public void onQuestDelFailure(int errorCode, String errorMsg) {

    }

    @Override
    public void onQuestDelSuccess() {
        // 通知其它界面数据改变
        amDataChangeManager.notifyRemove(questId);
        this.finish();
    }

    @Override
    public void onQuestDetailFailure(int errorCode, String errorMsg) {

    }

    @Override
    public void onQuestDetailSuccess(QaResponse response) {
        if (null != response) {
            display(response);
        }
    }

    @Override
    public void commentLongClick(final QuestAnswerListData data) {
        deleteManager.delete(data.id);
        adapter.deleteById(data.id);
        // 删除后，回复数减一
        resp.answerCount--;
        Utils.showPriseCounts(resp.answerCount, answerTV);
        amDataChangeManager.replyNotify(questId, resp.answerCount);
    }

    class MyItemClickListener implements OnItemClickListener {

        private ArrayList<String> url;

        public MyItemClickListener(ArrayList<String> url) {
            this.url = url;
        }

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            // TODO Auto-generated method stub
            // 弹出图片查看按钮
            imageBrower(position, url);
        }
    }

    /**
     * 打开图片查看器
     *
     * @param position
     * @param urls2
     */
    protected void imageBrower(int position, ArrayList<String> urls2) {
        Utils.imageBrower(this, position, urls2);
    }

    private void updateCounts(QuestAnswerCountsData qacd) {
        if (null != qacd) {
            resp.goodCount = qacd.goodCount;
            resp.answerCount = qacd.answerCount;
            resp.visitorCount = qacd.visitorCount;
            Utils.showVisitorCounts(qacd.visitorCount, visitorTV);
            Utils.showPriseCounts(qacd.goodCount, praiseTV);
            Utils.showPriseCounts(qacd.answerCount, answerTV);
            // 通知界面 浏览数发生更新
            amDataChangeManager.updateVisitor(questId, qacd.visitorCount);
            // 通知界面 点赞数发生更新
            amDataChangeManager.priseNotify(questId,resp.isGood, qacd.goodCount);
            // 通知界面 回复数发生更新
            amDataChangeManager.replyNotify(questId, qacd.answerCount);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.include_delete_tv:
                CustomDialog.Builder builder = new CustomDialog.Builder(AmDetailActivity.this);
                builder.setTitle("确认删除该条问答吗？");
                builder.setPositiveButton(getResources().getString(R.string.confirm),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                questDelManager.deleteQuest(GlobalContext.getAccountId(), questId);
                            }
                        });
                builder.setNegativeButton(getResources().getString(R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                builder.create().show();
                break;
            case R.id.back_button:
                finish();
                break;
            case R.id.include_forward_tv:    // 转发
                String imageUrl = GlobalContext.cdndownUrl + resp.headPic;
                ShareSDKManager shareSDKManager = ShareSDKManager.getInstance();
                shareSDKManager.showShare(AmDetailActivity.this, resp.content, 1, imageUrl, questId);
                break;
            case R.id.include_praise_tv:
                if (0 == resp.isGood) {
                    resp.isGood = 1;
                    resp.goodCount++;
                } else {
                    resp.isGood = 0;
                    resp.goodCount--;
                }
                Utils.praiseChanged(this, resp.isGood, resp.goodCount, praiseTV);
                amDataChangeManager.priseNotify(questId, resp.isGood, resp.goodCount);
                // 请求点赞接口
                praiseManger = new PraiseManger(this);
                praiseManger.addPraiseListener(AmDetailActivity.this);
                praiseManger.praise(GlobalContext.getAccountId(), questId);
                // 判断以前点赞状态
                break;
            case R.id.right_imagebutton:
                showRealase();
                break;
            case R.id.custom_qa_btn:
                if (null != dialog && dialog.isShowing()) {
                    dialog.dismiss();
                }
                if (checkLevel()) {
                    Intent ask = new Intent();
                    ask.setClass(AmDetailActivity.this, AskActivity.class);
                    startActivity(ask);
                } else {
                    ErrorDialogHelper.getInstance().showPerfectAuth(this);
                }
                break;
            case R.id.custom_am_btn:
                Intent anonymous = new Intent();
                anonymous.setClass(AmDetailActivity.this, AmQuestionActivity.class);
                startActivity(anonymous);
                if (null != dialog && dialog.isShowing()) {
                    dialog.dismiss();
                }
                break;
            case R.id.close_Dialog:
                if (null != dialog && dialog.isShowing()) {
                    dialog.dismiss();
                }
                break;
            default:
                break;
        }

    }

    public boolean checkLevel() {
        boolean ret = false;
        if (GlobalContext.getPerfectData()) {
            // 提示用户完成认证 必须达到一级认证才能提问
            ret = true;
        }
        return ret;
    }

    /**
     * 显示弹出框
     */
    private void showRealase() {
        commentLongClickHelper.showReportDialog(this,ReportType.TYPE_QA,questId);
    }

    @Override
    public void onPraiseFailure(int errorCode, String errorMsg) {

    }

    @Override
    public void onPraiseSuccess() {

    }

    @Override
    public void onQuestAnswerFailure(int errorCode, String errorMsg) {
        // ErrorMsgHandler.getInstance().onErrorMsg(this, errorCode, errorMsg);
        if (null != dialog && dialog.isShowing()) {
            dialog.dismiss();
        }

    }

    @Override
    public void onQuestAnswerSuccess(QuestAnswerListData qacd) {
        // TODO Auto-generated method stub
        if (null != dialog && dialog.isShowing()) {
            dialog.dismiss();
        }
        // 评论完成 添加一条记录到回复列表
        if (null != qacd) {
            bar_edit_text.setText("");
            bar_edit_text.setHint(getResources().getString(R.string.qa_detail_hint));
            if(null != replyMap){
                replyMap.clear();
            }
            qacd.accountId = GlobalContext.getAccountId();
            qacd.goodCount = 0;
            adapter.addOneData(qacd);
            adapter.notifyDataSetChanged();
            // 添加一条回答数
            resp.answerCount++;
            Utils.showPriseCounts(resp.answerCount, answerTV);
            // 通知界面更新回答列表
            amDataChangeManager.replyNotify(questId, resp.answerCount);
            mScrollView.fullScroll(ScrollView.FOCUS_UP);
            setListViewHeightBasedOnChildren(myListView);
//			new Handler().post(new Runnable() {
//				@Override
//				public void run() {
//				}
//			});
        }
    }

    @Override
    public void onQuestAnswerListFailure(int errorCode, String errorMsg) {
        if(errorCode == ErrorCode.QA_ALEARY_DEL){
            waittingLayout.setVisibility(View.VISIBLE);
            waittingProBar.setVisibility(View.GONE);
            waittingTV.setText(errorMsg == null ? "" : errorMsg);
            mPullToRefreshView.onFooterRefreshComplete();
            // 问答已被删除 通知其它界面数据改变
            amDataChangeManager.notifyRemove(questId);
        }else{
            waittingLayout.setVisibility(View.VISIBLE);
            waittingProBar.setVisibility(View.GONE);
            waittingTV.setText("加载失败，请稍后再试...");
            mPullToRefreshView.onFooterRefreshComplete();
        }
    }

    @Override
    public void onQuestAnswerListSuccess(List<QuestAnswerListData> objdata, QuestAnswerCountsData qacd) {
        waittingLayout.setVisibility(View.GONE);
        mPullToRefreshView.onFooterRefreshComplete();
        if (null != objdata) {
            adapter.addData(objdata, qacd);
            mList = adapter.getList();
            adapter.notifyDataSetChanged();
            if(0 == currentPage){
                mScrollView.fullScroll(ScrollView.FOCUS_UP);
            }
            setListViewHeightBasedOnChildren(myListView);
            updateCounts(qacd);
        }
    }

    private void display(QaResponse response) {
        this.resp = response;
        if (TextUtils.isEmpty(resp.realName)) {
            aliasNameTV.setVisibility(View.GONE);
        } else {
            aliasNameTV.setVisibility(View.VISIBLE);
            aliasNameTV.setText(resp.realName == null ? "" : "匿名者：" + resp.realName);
        }
        if (resp.accountId == GlobalContext.getAccountId()) {
            deleteTV.setVisibility(View.VISIBLE);
        } else {
            deleteTV.setVisibility(View.INVISIBLE);
        }
        contentTV.setMovementMethod(LinkMovementMethod.getInstance());
        contentTV.setAutoLinkMask(Linkify.WEB_URLS);
        contentTV.setText(resp.content == null ? "" : resp.content);
        contentTV.setOnLongClickListener(longClickListener);
        Utils.showVisitorCounts(resp.visitorCount, visitorTV);
        Utils.showPriseCounts(resp.answerCount, answerTV);
        Utils.praiseChanged(this, resp.isGood, resp.goodCount, praiseTV);
        // 通知界面 浏览数发生更新
        amDataChangeManager.updateVisitor(resp.id, resp.visitorCount);
        // 通知界面 点赞数发生更新
        amDataChangeManager.priseNotify(resp.id, resp.isGood, resp.goodCount);
        // 通知界面 回复数发生更新
        amDataChangeManager.replyNotify(resp.id, resp.answerCount);

        if (TextUtils.isEmpty(resp.questImgs)) {
            mGridView.setVisibility(View.GONE);
        } else {
            mGridView.setVisibility(View.VISIBLE);
            ArrayList<String> imageUrls = PictureDownloadUtils.getInstance().stringToList(resp.questImgs);
            double multiple = Math.ceil((float) imageUrls.size() / GlobalContext.NUMCOLUMNS);
            int height = (int) (Utils.dip2px(this, 80) * multiple + (multiple - 1) * Utils.dip2px(this, 10));
            int width = 0;
            if (multiple >= 1) {
                width = Utils.dip2px(this, 80) * GlobalContext.NUMCOLUMNS + (GlobalContext.NUMCOLUMNS - 1) * Utils.dip2px(this, 5);
            } else {
                width = Utils.dip2px(this, 80) * imageUrls.size() + (imageUrls.size() - 1) * Utils.dip2px(this, 5);
            }
            width = width + Utils.dip2px(this, 10);// 加上pendingLeft 10dp
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(width, height);
            mGridView.setLayoutParams(lp);
            mGridView.setAdapter(new NoScrollGridAdapter(this, imageUrls));
            // 点击回帖九宫格，查看大图
            mGridView.setOnItemClickListener(new MyItemClickListener(imageUrls));
        }

    }

    @Override
    public void onAnswerDeleteFailure(int errorCode, String errorMsg) {
    }

    @Override
    public void onAnswerDeleteSuccess() {
    }

    OnLongClickListener longClickListener = new OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {
            showCopyDialog();
            return true;
        }
    };

    /**
     * 显示复制取消弹出框
     */
    private void showCopyDialog() {
        commentLongClickHelper.showCopyDialog(this,contentTV.getText().toString());
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    public void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        int totalHeight = 0;
        for (int i = 0, len = adapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = adapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (adapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

    /* (non-Javadoc)		上拉刷新...
     * @see com.wbao.dianniu.scrollview.PullToRefreshView.OnFooterRefreshListener#onFooterRefresh(com.wbao.dianniu.scrollview.PullToRefreshView)
     */
    @Override
    public void onFooterRefresh(PullToRefreshView view) {
        // TODO Auto-generated method stub
        pullUpRequest();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ReplyHelper.getInstance().removeReplyListener(this);
        if(null != commentLongClickHelper)
            commentLongClickHelper.removeCommentLongClickListener(this);
        if (null != dialog && dialog.isShowing()) {
            dialog.dismiss();
        }
        if (null != questDetailManager) {
            questDetailManager.removeQuestDetailListener(this);
        }
        if (null != manager) {
            manager.removeListener(this);
        }
        if (null != deleteManager) {
            deleteManager.removeAnswerDeleteListener(this);
        }
        if (null != qAnswerManager) {
            qAnswerManager.removeQuestAnswerListener(this);
        }
        if (null != questDelManager) {
            questDelManager.removeQuestDelListener(this);
        }
        if (null != praiseManger) {
            praiseManger.removePraiseListener(this);
        }
    }

    @Override
    public void reply(String userName, int userId) {
        bar_edit_text.setText("");
        bar_edit_text.setHint("回复:" + userName);
        bar_edit_text.requestFocus();
        bar_edit_text.post(new Runnable() {
            @Override
            public void run() {
                mInputManager.showSoftInput(bar_edit_text, 0);
            }
        });
        // add Reply logical
        replyMap = new HashMap<Integer, String>();
        replyMap.put(userId, userName);
    }

    TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if(s.length() == 0){
                // 清空输入内容时，清除@效果的hashMap
                bar_edit_text.setHint(getResources().getString(R.string.qa_detail_hint));
                if(null != replyMap){
                    replyMap.clear();
                }
            }
        }
    };

    float previousX = 0;
    float previousY = 0;
    float softHeight = 0;
    boolean inOutside = true;

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()){
            case MotionEvent.ACTION_DOWN:
                previousX = ev.getRawX();
                previousY = ev.getRawY();
                int[] l = {0, 0};
                bar_image_add_btn.getLocationInWindow(l);
                softHeight = l[1];
                if (ev.getY() < softHeight) {
                    inOutside = true;
                } else {
                    inOutside = false;
                }
                break;
            case MotionEvent.ACTION_MOVE:
                float dy = previousY - ev.getRawY();
                float dx = previousX - ev.getRawX();
                if((Math.abs(dy)> 30 || Math.abs(dx) > 30) && inOutside ){
                    hideKeyboard();
                }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     */
    private void hideKeyboard() {
        emotionMainFragment.onBackPress();
    }

}
